package com.ithuameng.admin.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Http 工具类 https://my.oschina.net/u/994081/blog/185982
 *
 * @author ithuameng
 */
@Slf4j
public class HttpUtil {

    private static final String URL_REGEXP = "((http[s]?)?(://))?([^/]*)(/?.*)";

    /**
     * 获取客户端IP
     *
     * @param request httpRequest
     * @return ip address
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        log.error("获取ip异常：{}", e.getMessage());
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割"***.***.***.***".length() = 15
            if (ipAddress != null && ipAddress.length() > 15) {
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        // ipAddress = this.getRequest().getRemoteAddr();
        return ipAddress;
    }

    /**
     * 提取URL中主机名部分
     *
     * @param url URL
     * @return 主机名
     */
    public static String getServerName(String url) {
        if (StringUtils.isNotBlank(url)) {
            url = url.trim();
            Pattern p = Pattern.compile(URL_REGEXP);
            Matcher m = p.matcher(url);
            if (m.matches()) {
                String domain = m.group(4);
                int colonIndex = domain.indexOf(":");
                if (colonIndex > 0) {
                    domain = domain.substring(0, colonIndex);
                }
                return domain;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String referer = "http://www.baidu.com:8080/test.html";
        Pattern p = Pattern.compile(URL_REGEXP);
        Matcher m = p.matcher(referer);
        if (m.matches()) {
            String domain = m.group(4);
            int colonIndex = domain.indexOf(":");
            if (colonIndex > 0) {
                domain = domain.substring(0, colonIndex);
            }
            System.out.println(domain);
        }
    }
}
